package bm35;

import javax.swing.tree.TreeNode;
import java.util.*;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/8/11 2:36
 * BM35. 判断是否为完全二叉树
 * https://www.nowcoder.com/practice/8daa4dff9e36409abba2adbe413d6fae?tpId=295&tqId=2288088&ru=%2Fpractice%2F8a2b2bf6c19b4f23a9bdb9b233eefa73&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Fojhttps://www.nowcoder.com/practice/8daa4dff9e36409abba2adbe413d6fae?tpId=295&tqId=2288088&ru=%2Fpractice%2F8a2b2bf6c19b4f23a9bdb9b233eefa73&qru=%2Fta%2Fformat-top101%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj
 */
public class Solution {

    // 层序遍历思路: 如果为完全二叉树, 只有在遍历完二叉树后才会有 null
    public boolean isCompleteTree (TreeNode root) {
        // 边界
        if (root == null) {
            return true;
        }
        // 层序遍历思路
        Deque<TreeNode> queue = new LinkedList<>(); // 不能使用 ArrayDeque 因为不能存 null 值
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode pollNode = queue.poll();
            if (pollNode == null) {
                // 如果该节点为空, 则直接退出循环
                break;
            }
            // 左右子树都存入队列, 即使是 null
            queue.offer(pollNode.left);
            queue.offer(pollNode.right);
        }
        // 判断队列剩余元素是否存在非空
        while (!queue.isEmpty()) {
            TreeNode pollNode = queue.poll();
            if (pollNode != null){
                return false;
            }
        }
        return true;
    }

    private static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
        public TreeNode(int val) {
            this.val = val;
        }
    }

//    public static void main(String[] args) {
//        Deque<TreeNode> queue = new LinkedList<>();
//        queue.offer(new TreeNode(-1));
//        System.out.println(queue.size());
//        queue.offer(null);
//        System.out.println(queue.size());
//    }
}
